/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <sf-form ref="form"
             class="add-algorithm__form"
             :label-width="100">
        <div class="form__title">
            <lang>基本信息</lang>
        </div>
        <sf-form-item>
            <sf-fieldlabel class="p-l0">
                <lang>模型名称</lang>
            </sf-fieldlabel>
            <sf-textfield
                ref="fieldName"
                v-model="submitData.name"
                :default-width="defaultWidth"
                :max-length="30"
                :allow-blank="false"
                :utf8-length="false"
                vtype="name"
                :blur-trim="true"
                :placeholder="_('请输入模型名称')" />
        </sf-form-item>
        <sf-form-item>
            <sf-fieldlabel class="p-l0">
                <lang>描述</lang>
            </sf-fieldlabel>
            <sf-textarea
                v-model="submitData.description"
                :placeholder="_('最多300字（选填）')"
                :default-width="defaultWidth"
                :max-length="300"
                :utf8-length="false" />
        </sf-form-item>
        <div class="form__title">
            <lang>模型文件配置</lang>
        </div>
        <sf-form-item>
            <sf-fieldlabel class="p-l0">
                <lang>选择模型文件</lang>
            </sf-fieldlabel>
            <sf-textfield
                ref="uploadTextField"
                v-model="submitData.file"
                :default-width="250"
                :placeholder="_('请选择模型文件')"
                :allow-blank="false"
                :default-disabled="true" />
            <sf-fileupload
                ref="fileUpload"
                class="sfv-btn-primary"
                :url="fileURL"
                :params="submitData"
                :accept="acceptFile"
                :auto-upload="false"
                @progress="handleProgress"
                @change="_selectFile"
                @uploadfile:failure="uploadFailure"
                @uploadfile:success="uploadSuccess">
                <lang>选择</lang>
            </sf-fileupload>
        </sf-form-item>
        <div class="uploadFile__tips">
            <span>{{ acceptFileText }}</span>
        </div>
    </sf-form>
</template>
<script lang="ts">
const DEFAULT_WIDTH = 336;
const DEFAULT_VALUE = {
    name: '',
    description: '',
    file:'',
    projectId: ''
};

interface FormData{
    name: string;
    description: string;
    file: string;
    fileMd5: string;
    projectId: string;
}

const MAX_SIZE = 2147483648; // 2GB

const ACEEPT_TYPE = ['.zip', '.tar.gz', '.jar'];
import { Component, Vue } from 'vue-property-decorator';
import store from 'src/vuex/store';
let userID = store.state.userId;

// import BMF from 'browser-md5-file';

import SparkMD5 from 'spark-md5';

@Component
export default class AddModelForm extends Vue {
    submitData = { ...DEFAULT_VALUE, fileMd5: '' }
    progress = 0

    // uploadParams = {
    //     fileMd5: ''
    // }

    get defaultWidth () {
        return DEFAULT_WIDTH;
    }
    get acceptFile () {
        return ACEEPT_TYPE.join(',');
    }
    get acceptFileText () {
        return _('支持扩展名：{0}，上传文件可能较慢，请耐心等候', ACEEPT_TYPE.join(' '));
    }
     get projectId () {
        return this.$route.query.projectId || '';
    }
    get fileURL () {
        return `training/v1/user/${userID}/model/file`;
    }

    // // 上传相关
    /* eslint-disable */
    _selectFile (files: File[]) {
        // @ts-ignore
        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
            file =  files[0],
            /* eslint-disable */
            chunkSize = MAX_SIZE,                             // Read in chunks of 2MB
            chunks = Math.ceil(file.size / chunkSize),
            currentChunk = 0,
            vm = this,
            spark = new SparkMD5.ArrayBuffer(),
            fileReader = new FileReader();
        this.$mask();
        if (!/.zip|.tar.gz|.jar$/.test(file.name)) {
            vm.$showErr(_('只支持上传{0}文件', vm.acceptFile));
            return false;
        }
        if (file.size > MAX_SIZE) {
            vm.$showErr(_('上传文件的体积应小于2GB'));
            return false;
        }
        fileReader.onload = function (e) {
            // @ts-ignore
            spark.append(e.target.result);                   // Append array buffer
            currentChunk++;
            if (currentChunk < chunks) {
                loadNext();
            } else {
                vm.$unmask();
                vm.submitData.file = file.name;
                vm.submitData.projectId = vm.projectId as string;
                vm.submitData.fileMd5 = spark.end() as string;
            }
        };

        fileReader.onerror = function () {
            vm.$unmask();
            vm.$showErr(_('上传失败'));
        };

        function loadNext() {
            let start = currentChunk * chunkSize,
                end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
        }

        loadNext();
    }

    /* eslint-disable */
    // @ts-ignore
    uploadSuccess (vm:SafeAny, result:SafeAny, file:SafeAny, jsonData:SafeAny) {
        this.$parent.options.uploadSuccessCallback(jsonData);
    }

    // @ts-ignore
    uploadFailure (vm:SafeAny, result:SafeAny, file:SafeAny, jsonData:SafeAny) {
        // @ts-ignore
        this.$refs.fileUpload.progressWindow && this.$refs.fileUpload.progressWindow.hide(); // 隐藏进度条
        this.$parent.options.uploadFailureCallback(jsonData);
    }

    handleProgress (loaded:number, total:number) {
        /* eslint-disable */
        this.progress = parseFloat((loaded / total).toFixed(2));
    }

    beginUpload () {
        let uploader = this.$refs.fileUpload;
        if (uploader) {
            // @ts-ignore
            uploader.uploadFile();
        }
    }
    getJsonValue () {
        return this.submitData;
    }
    setJsonValue (data:FormData) {
        Object.assign(this.submitData, data);
    }
  };
  </script>
  <style lang="less" scoped>
  .add-algorithm__form {
    .form__title{
        font-size: 13px;
        color: #14161A;
        font-weight:bolder;
        margin-bottom:10px;
    }
    .model-tips {
      background-color: #fdf3e4;
      color: #e0720b;
      padding: 10px;
      margin-bottom: 10px;
      text-align: center;
    }
    .label-form__tabel {
      border: none;
    }
    .uploadFile {
      display: flex;
      align-items: center;
      .sfv-btn-primary {
        margin-left: 8px;
      }
    }
    .uploadFile__tips {
      padding-left: 105px;
      margin-top: -8px;
      margin-bottom: 12px;
      color: #a3a3a3;
      .upload-download{
          color: #204ed9;
          margin-left: 108px;
      }
    }
  }
  </style>
